package com.huahai.security.core.validate.code.image;

import com.huahai.security.core.properties.SecurityConstants;
import com.huahai.security.core.properties.StatusCodeEnum;
import com.huahai.security.core.supports.ResultResponse;
import com.huahai.security.core.validate.code.impl.AbstractValidateCodeProcessor;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2020/7/17
 * <p>
 * 图片验证码处理器
 */
@Component("imageValidateCodeProcessor")
public class ImageCodeProcessor extends AbstractValidateCodeProcessor<ImageCode> {

    /**
     * 发送图形验证码，将其写到响应中
     */
    @Override
    protected ResultResponse send(HttpServletRequest request, HttpServletResponse response, ImageCode imageCode) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(imageCode.getImage(), "jpeg", outputStream);
        String base64Image = SecurityConstants.DEFAULT_BASE64_IMAGE_PREFIX + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        Map<String,Object> map = new HashMap<>(2);
        map.put("uuid", imageCode.getUuid());
        map.put("imageUrl", base64Image);
        return ResultResponse.build(StatusCodeEnum.HSC200000.getCode(),StatusCodeEnum.HSC200000.getMessage(),map);
    }

}
